<!DOCTYPE html>
<html lang="zh-cn">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>IYUUPlus开发版 - 登录</title>
    <!-- 样 式 文 件 -->
    <link rel="stylesheet" href="/app/admin/component/pear/css/pear.css"/>
    <link rel="stylesheet" href="/app/admin/admin/css/pages/login.css"/>
</head>
<!-- 代 码 结 构 -->
<body style="background-size: cover; background-image: url(/app/admin/admin/images/background.svg)">
<form class="layui-form">
    <div class="layui-form-item">
        <img class="logo" src="/app/admin/admin/images/logo.png"/>
        <div class="title pear-text">IYUUPlus</div>
    </div>
    <div class="layui-form-item">
        <input lay-verify="required" hover class="layui-input" type="text" name="username" value=""
               placeholder="用户名"/>
    </div>
    <div class="layui-form-item">
        <input lay-verify="required" hover class="layui-input" type="password" name="password" value=""
               placeholder="密码"/>
    </div>
    <div class="layui-form-item">
        <input hover lay-verify="required" class="code layui-input layui-input-inline" name="captcha"
               placeholder="验证码"/>
        <img class="codeImage" width="120px"/>
    </div>
    <div class="layui-form-item">
        <button type="submit" class="pear-btn pear-btn-primary login" lay-submit lay-filter="login">
            登 入
        </button>
    </div>
    <!-- 添加忘记密码链接 -->
    <div class="layui-form-item">
        <button type="button" class="layui-btn layui-btn-sm layui-btn-disabled" id="oauth_login" lay-on="oauth_login">
            <i class="layui-icon layui-icon-login-wechat"></i> 微信扫码登录
        </button>
        <a href="https://doc.iyuu.cn/guide/qa-iyuuplus#reset-password" target="_blank" class="pear-text"
           style="display: block; text-align: center; color: #2d8cf0;">
            忘记密码？
        </a>
    </div>
</form>
<script>
    var color = localStorage.getItem("theme-color-color");
    var second = localStorage.getItem("theme-color-second");
    if (!color || !second) {
        localStorage.setItem("theme-color-color", "#2d8cf0");
        localStorage.setItem("theme-color-second", "#ecf5ff");
    }
</script>
<!-- 资 源 引 入 -->
<script src="/app/admin/component/layui/layui.js?v=2.8.12"></script>
<script src="/app/admin/component/pear/pear.js"></script>
<script src="/push.js"></script>
<script>
    layui.use(['form', 'button', 'popup', 'layer', 'theme', 'admin', 'util'], function () {
        var $ = layui.$, layer = layui.layer, form = layui.form, util = layui.util;

        // 爱语飞飞服务器域名
        const IYUU_HOST = 'https://iyuu.cn';
        // 获取Pusher长连接配置
        const IYUU_PUSH_CONFIG = IYUU_HOST + '/plugin/ledc/push/config';
        // 获取带参数二维码
        const IYUU_QRCODE_CREATE = IYUU_HOST + '/qrcode/create?scene=oauth&force_refresh=1';
        // 登录验证
        const IYUU_ACCOUNT_LOGIN = '/admin/account/index';
        // 登录按钮
        let oauthLoginElem = document.getElementById('oauth_login');
        // pusher长连接对象
        let iyuuPusher = null;

        function switchCaptcha() {
            $('.codeImage').attr("src", "/app/admin/account/captcha/login?v=" + new Date().getTime());
        }

        switchCaptcha();
        // 登 录 提 交
        form.on('submit(login)', function (data) {
            layer.load();
            $.ajax({
                url: '/app/admin/account/login',
                type: "POST",
                data: data.field,
                success: function (res) {
                    layer.closeAll('loading');
                    if (!res.code) {
                        layui.popup.success('登录成功', function () {
                            location.reload();
                        })
                    } else {
                        layui.popup.failure(res.msg)
                        switchCaptcha();
                    }
                }
            });
            return false;
        });
        $('.codeImage').on('click', function () {
            switchCaptcha();
        });

        util.on('lay-on', {
            oauth_login: function () {
                if (oauthLoginElem.classList.contains('layui-bg-orange')) {
                    layui.layer.msg('长连接已断线，不支持扫码登录');
                    return false;
                }
                fetchChannelNameOrQrcode();
            },
        });
        requestPusherConfig();

        /**
         * 请求长连接配置信息
         */
        function requestPusherConfig() {
            $.ajax({
                url: IYUU_PUSH_CONFIG,
                dataType: 'json',
                success: function (res) {
                    if (res.code) {
                        return layui.popup.failure(res.msg);
                    }
                    localStorage.setItem('iyuu_push_config', JSON.stringify(res.data));
                    iyuuPusher = new Push(res.data);
                    setInterval(() => {
                        if (iyuuPusher.connection.state === 'connected') {
                            oauthLoginElem.classList.remove('layui-btn-disabled');
                            oauthLoginElem.classList.remove('layui-bg-orange');
                        } else {
                            layui.layer.closeAll('page');
                            iyuuPusher.unsubscribeAll();
                            oauthLoginElem.classList.add('layui-bg-orange');
                        }
                    }, 2000);
                }
            });
        }

        /**
         * 请求唯一私有频道和二维码
         * @returns {Promise<any>}
         */
        function fetchChannelNameOrQrcode() {
            fetch(IYUU_QRCODE_CREATE, {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            })
                .then(response => response.json())
                .then(res => {
                    if (res.code) {
                        layui.layer.msg(res.msg);
                        throw new Error('响应失败');
                    }
                    console.log('成功获取二维码:', res);
                    listenChannel(res.data.channel_name);
                    return res.data;
                })
                .then(res => {
                    showQrcode(res['ticket'], res['expire_seconds'], res['channel_name']);
                })
                .catch(error => {
                    console.error('请求失败:', error);
                });
        }

        /**
         * 监听频道
         * @param channel_name
         */
        function listenChannel(channel_name) {
            let uniqid_channel = iyuuPusher.subscribe(channel_name);
            uniqid_channel.on('oauth_login', function (data) {
                layui.layer.closeAll('page');
                data.key = channel_name;
                console.info(data);
                layui.$.ajax({
                    url: IYUU_ACCOUNT_LOGIN,
                    type: "POST",
                    dateType: "json",
                    data: data,
                    success: function (res) {
                        if (res.code) {
                            return layui.popup.failure(res.msg);
                        }
                        layui.popup.success('登录成功', function () {
                            location.reload();
                        })
                    }
                });
            });
        }

        /**
         * 显示二维码
         * @param {string} ticket
         * @param {int} expire_seconds
         * @param {string} channel_name
         */
        function showQrcode(ticket, expire_seconds, channel_name) {
            layer.open({
                type: 1,
                id: 'oauth_login',
                area: ['auto'],
                title: '请用微信扫码',
                time: expire_seconds * 1000,
                shade: 0.9, // 遮罩透明度
                anim: 0, // 0-6 的动画形式，-1 不开启
                content: '<div style="display: flex;justify-content: center;align-items: center;"><img src="https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=' + ticket + '" width="300px" height="300px" alt="二维码" /></div>',
                success: function (layero, index) {
                    let timeNum = this.time / 1000, setText = function (start) {
                        layer.title('请用微信扫码，二维码<span class="layui-font-red">' + (start ? timeNum : --timeNum) + '</span>秒过期', index);
                    };
                    setText(!0);
                    this.timer = setInterval(setText, 1000);
                    if (timeNum <= 0) clearInterval(this.timer);
                },
                end: function () {
                    iyuuPusher.unsubscribe(channel_name);
                    clearInterval(this.timer);
                }
            });
        }
    })
</script>
</body>
</html>
